﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Net.Http.Formatting;
using System.ServiceModel;
using System.Web.Http;
using System.Web.Http.SelfHost;
using Newtonsoft.Json.Serialization;
using Topshelf;

namespace LuceneApiServer
{
    public class HttpApiService : ServiceControl
    {
        private const string EventSource = "LuceneHttpApiService";
        private HttpSelfHostConfiguration _config;
        private HttpSelfHostServer _server;

        public bool Start(HostControl hostControl)
        {
            var address = new Uri(ConfigurationManager.AppSettings["Uri"]);
            if (!EventLog.SourceExists(EventSource))
            {
                EventLog.CreateEventSource(EventSource, "Application");
            }
            EventLog.WriteEntry(EventSource,
                string.Format("Creating Lucene.net server at {0}",
                    address));
            _config = new HttpSelfHostConfiguration(address);
            #region web api  datatype 配置

            _config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            _config.Formatters.JsonFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("datatype", "json", "application/json"));

            _config.Formatters.XmlFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("datatype", "xml", "application/xml"));
            var serializerSettings = _config.Formatters.JsonFormatter.SerializerSettings;
            var contractResolver = (DefaultContractResolver)serializerSettings.ContractResolver;
            contractResolver.IgnoreSerializableAttribute = true;

            #endregion
            //路由
            _config.Routes.MapHttpRoute("DefaultApi",
                "{controller}/{id}",
                new { id = RouteParameter.Optional }
                );
            #region 远程服务器返回了意外响应: (413) Request Entity Too Large
            _config.MaxBufferSize = 2147483647;//默认64 * 1024= 65536 B
            _config.MaxReceivedMessageSize = 2147483647;
            _config.TransferMode = TransferMode.Streamed;
            #endregion
            
         //   _config.ReceiveTimeout = new TimeSpan(50000000);//5秒  默认10分钟
            //启用跨域　　
            _config.EnableCors();
            _config.MaxConcurrentRequests = 10000;//默认100
            _server = new HttpSelfHostServer(_config);
            EventLog.WriteEntry(EventSource, "Opening Lucene.net HttpApiService server.");
            _server.OpenAsync().Wait();
            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            if (_server != null)
            {
                _server.CloseAsync().Wait();
                _server.Dispose();
            }
            if (_config != null)
            {
                _config.Dispose();
            }
            return true;
        }
    }
}